package com.mobilebook.properties;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class GlobalPropertyPlaceholderConfigurer extends
PropertyPlaceholderConfigurer {

	private File confDirFile;
	private Properties props;
	
	public String getConfigPath() {
		//String dirPath = System.getProperty("service.config.path");
		//return dirPath;
		return confDirFile.getAbsolutePath();
	}
	
	public String getProperty(String key) {
		if (props == null)
			throw new RuntimeException("GlobalPropertyPlaceholderConfigurer init failed.");
		return props.getProperty(key);
	}
	
	public void setConfChildPath(String confChildPath) {
		String dirPath = System.getProperty("service.config.path");
		if (dirPath == null)
			throw new RuntimeException("Must set JVM startup property service.config.path");
		
		confDirFile = new File(dirPath, confChildPath);
		if (! confDirFile.exists())
			throw new RuntimeException("Config directory <"+ confDirFile.getAbsolutePath() +"> doesn't exists.");
		
		String[] files = confDirFile.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (! name.endsWith(".properties")) {
					return false;
				}
				return true;
			}
		});
		
		Resource[] locations = new Resource[files.length];
		for (int i=0; i < files.length; i++) {
			locations[i] = new FileSystemResource(new File(confDirFile, files[i]));
		}
		super.setLocations(locations);
	}
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
		props.put("config_path", getConfigPath());
		this.props = props;
		super.processProperties(beanFactoryToProcess, props);
	}
	
	public static Hashtable<String, String> loadProperties(File propFile) {
		if (! propFile.exists())
			throw new RuntimeException("Config file <"+ propFile.getAbsolutePath() +"> doesn't exists.");
		Properties prop = new Properties();
		try {
			InputStream is = new FileInputStream(propFile);
			prop.load(is);
			is.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		Hashtable<String, String> result = new Hashtable<String, String>();
		for (Object okey : prop.keySet()) {
			String key = (String)okey;
			String value = prop.getProperty(key);
			result.put(key, value);
		}
		return result;
	}
}

